package models

import (
	"gorm.io/gorm"
	"social-app/dao"
	"time"
)

type User struct {
	Id         int       `json:"id"`
	Username   string    `json:"username"`
	Password   string    `json:"password"`
	Openid     string    `json:"openid"`
	CreateTime time.Time `json:"create_time" gorm:"autoCreateTime"`
	UpdateTime time.Time `json:"update_time" gorm:"autoUpdateTime"`
}

func (u *User) TableName() string {
	return "user"
}

func GetUserByUsername(username string) (User, error) {
	var user User
	err := dao.Db.Where("username = ?", username).Where("is_del = ?", 0).First(&user).Error
	return user, err
}

func GetUserByOpenId(openId string) (User, error) {
	var user User
	err := dao.Db.Where("openid = ?", openId).Where("is_del = ?", 0).First(&user).Error
	return user, err
}

func CreateUser(username string, password string, regIp string, openId string) User {
	user := User{
		Username: username,
		Password: password,
		Openid:   openId,
	}
	dao.Db.Transaction(func(tx *gorm.DB) error {
		err := tx.Create(&user).Error
		if err != nil {
			return err
		}
		return CreateUserProfile(user.Id, regIp)
	})
	return user
}

func GetUserById(id int) (User, error) {
	var user User
	err := dao.Db.Where("id = ?", id).Where("is_del = ?", 0).First(&user).Error
	return user, err
}
